package com.study.system.controller;

import com.study.system.dto.ResultData;
import com.study.system.entity.Admin;
import com.study.system.entity.Club;
import com.study.system.entity.User;
import com.study.system.enums.ResultCode;
import com.study.system.exception.UserAccountRecurException;
import com.study.system.exception.UserNotExistException;
import com.study.system.exception.UserVerifyException;
import com.study.system.service.UserService;
import com.study.system.utils.RequestUtil;
import com.study.system.vo.UserInfoVO;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    /**
     * 用户登录Controller
     *
     * @param userinfo 用户输入信息JSON
     * @return 身份验证token
     */
    @PostMapping("/login")
    public ResultData<String> login(@RequestBody Map<String, String> userinfo) {
        String account = userinfo.get("account");
        String password = userinfo.get("password");
        String role = userinfo.get("role");

        ResultData<String> resultData;
        try {
            String token = userService.login(account, password, role);
            resultData = ResultData.success(token);
        } catch (UserNotExistException e) {
            resultData = ResultData.fail(ResultCode.LOGIN_USER_NO_EXIST);
        } catch (UserVerifyException e) {
            resultData = ResultData.fail(ResultCode.LOGIN_PASSWORD_FAIL);
        }

        return resultData;
    }

    /**
     * 用户注册Controller
     *
     * @param user 前端提交数据
     * @return 操作状态
     */
    @PostMapping("/register")
    public ResultData<Boolean> register(@RequestBody User user) {
        ResultData<Boolean> resultData;
        try {
            if (userService.register(user)) {
                resultData = ResultData.success(true);
            } else {
                resultData = ResultData.fail(ResultCode.DATABASE_ERROR);
            }
        } catch (UserAccountRecurException e) {
            resultData = ResultData.fail(ResultCode.REGISTER_ACCOUNT_RECUR);
            return resultData;
        }

        return resultData;
    }

    /**
     * 修改用户信息
     *
     * @param request 前端发送的请求
     * @param user    前端发送的数据
     * @return 返回操作是否成功
     */
    @PostMapping("/modify_info")
    public ResultData<Boolean> modifyUserInfo(HttpServletRequest request, @RequestBody User user) {
        // 获取用户id
        Integer userId = RequestUtil.getUserId(request);
        user.setId(userId);
        if (userService.modifyUserInfo(user))
            return ResultData.success(true);
        return ResultData.fail(ResultCode.DATABASE_ERROR);
    }

    @PostMapping ("/adminModifyUserInfo")
    public ResultData<Boolean> adminModifyUserInfo(@RequestBody User user) {
        System.out.println(user);
        return ResultData.success(userService.adminModifyUserInfo(user));
    }

    /**
     * 修改用户密码
     *
     * @param request 请求头（携带token信息）
     * @param newInfo 新的密码
     * @return 操作是否成功
     */
    @PostMapping("/modify_password")
    public ResultData<Boolean> modifyUserPassword(HttpServletRequest request, @RequestBody Map<String, String> newInfo) {
        Boolean result = userService.modifyUserPassword(RequestUtil.getUserId(request), newInfo.get("newPassword"), newInfo.get("role"));
        return result ? ResultData.success(true) : ResultData.fail(ResultCode.PASSWORD_RE);
    }

    /**
     * 用户注销
     *
     * @param request 前端发送请求
     * @return 操作是否成功
     */
    @GetMapping("/delete")
    public ResultData<Boolean> deleteUser(HttpServletRequest request) {
        return ResultData.success(userService.deleteUser(RequestUtil.getUserId(request)));

    }

    /**
     * 查询指定社团的全部用户
     *
     * @param clubInfo 社团信息（只需要社团Id）
     * @return 查询结果
     */
    @PostMapping("/show_club_all_user")
    public ResultData<List<UserInfoVO>> getUserList(@RequestBody Club clubInfo) {
        return ResultData.success(userService.findClubAllUser(clubInfo.getId()));
    }

    /**
     * 判断用户身份
     *
     * @param request 请求头，携带token信息
     * @return 判断结果
     */
    @PostMapping("/identify_post")
    public ResultData<Boolean> identifyPost(HttpServletRequest request, @RequestBody Map<String, Integer> clubInfo) {
        return ResultData.success(userService.identifyPost(clubInfo.get("clubId"), RequestUtil.getUserId(request)));
    }

    /**
     * 获取用户个人信息
     *
     * @param request 前端请求头
     * @return 用户个人信息
     */
    @GetMapping("/get_personal_info")
    public ResultData<UserInfoVO> getUserPersonalInfo(HttpServletRequest request) {
        return ResultData.success(userService.getUserPersonalInfo(RequestUtil.getUserId(request)));
    }

    /**
     * 获取指定用户的职位名称
     *
     * @param request  请求头（只需要token）
     * @param clubInfo 社团信息（只需要社团ID）
     * @return 职位名称
     */
    @PostMapping("/get_user_post")
    public ResultData<String> getUserPostINClub(HttpServletRequest request, @RequestBody Map<String, Integer> clubInfo) {
        return ResultData.success(userService.getUserPostInClub(RequestUtil.getUserId(request), clubInfo.get("clubId")));
    }

    @PostMapping("/allUserInfo")
    public ResultData<List<User>> getAllUserInfo(@RequestBody Map<String, Integer> limitInfo) {
        return ResultData.success(userService.getAllUserInfo(limitInfo.get("pageSize"), limitInfo.get("currentIndex")));
    }

    @GetMapping("/allUserNumber")
    public ResultData<Integer> getAllUserNumber() {
        return ResultData.success(userService.getAllUserNumber());
    }

    @GetMapping("/getAdminInfo")
    public ResultData<Admin> getAdminInfo(HttpServletRequest request) {
        return ResultData.success(userService.getAdminInfo(RequestUtil.getUserId(request)));
    }

    @PostMapping("/searchClubMemberByName")
    public ResultData<List<UserInfoVO>> searchClubMemberByName(@RequestBody Map<String, String> map) {
        return ResultData.success(userService.searchClubMemberByName(map));
    }

    @PostMapping("resetPassword")
    public ResultData<Boolean> resetPassword(@RequestBody User user) {
        return ResultData.success(userService.resetPassword(user));
    }
}
